//AUTHOR: Kevin Lam

var login_req = getXmlHttpRequestObject();

function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("IE5/6 not supported");
	}
}

function tryLogin() {
	if (login_req.readyState == 4 || login_req.readyState == 0) {
		login_req.open("POST", 'ajax/login', true);
		var username = document.getElementById('username').value;
		var password = document.getElementById('password').value;
		var params = "&username="+username+"&password="+password;
		login_req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		login_req.onreadystatechange = handleLogin;
		login_req.send(params);
	}
}

function handleLogin() {
	if (login_req.readyState == 4) {
		var xmlDoc = login_req.responseXML.documentElement;
		var login = xmlDoc.getElementsByTagName("login")[0].childNodes[0].nodeValue;
		if(login == 'true') {
			var user = xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
			var auth = xmlDoc.getElementsByTagName("key")[0].childNodes[0].nodeValue;
			setCookie('user',user, 1);
			setCookie('auth',auth, 1);
			location.reload(true);
		}
		else {
			var error = xmlDoc.getElementsByTagName("error")[0].childNodes[0].nodeValue;
			var error_msg = '<p class="error_text">'+error+'</p>';
			var error_content = document.getElementById('error');
			error_content.innerHTML = error_msg;
			$('#error').fadeIn(500).delay(3000).fadeOut(500);
		}
		

	}
}

function keyPressed(event){
	if(event.keyCode == 13){
		tryLogin();
	}
}

function setCookie(c_name, value, exdays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value = escape(value)
			+ ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
	document.cookie = c_name + "=" + c_value;
}

function hideError(){
	document.getElementById('error').className = 'error_hide';
}